package com.medaxis.hpams.sso.service.impl;

import com.medaxis.hpams.sso.common.RedisCache;
import com.medaxis.hpams.sso.constant.Constants;
import com.medaxis.hpams.sso.domain.dto.LoginUser;
import com.medaxis.hpams.sso.exception.CaptchaException;
import com.medaxis.hpams.sso.exception.CaptchaExpireException;
import com.medaxis.hpams.sso.manager.AsyncManager;
import com.medaxis.hpams.sso.manager.factory.AsyncFactory;
import com.medaxis.hpams.sso.service.LoginService;
import com.medaxis.hpams.sso.utils.i18n.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 */
@Component
public class LoginServiceImpl implements LoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;
//
    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    @Override
    public String login(String username, String password, String code, String uuid) {
        //todo 用户登录
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            // todo 记录登录日志
//            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            try {
                throw new CaptchaExpireException();
            }catch (CaptchaExpireException c){
                return "0";
            }
        }
        if (!code.equalsIgnoreCase(captcha)) {
//            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            try {
                throw new CaptchaException();
            }catch (CaptchaException c){
                return "1";
            }

        }

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            return "2";
        }
//        AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
